import { Message } from '@teamix/ui';
import { NameSpace } from 'utils/index';
import exceed from 'utils/apimap';
import intl from '../../../../../../../../../locale';

const { organization, remoteIP } = window.FORCE;
const ns = NameSpace('security');
export const RECEIVE_IP_WHITE_CHECK = ns('RECEIVE_IP_WHITE_CHECK');
export const RECEIVE_LAST_IP_WHITE_CHECK = ns('RECEIVE_LAST_IP_WHITE_CHECK');
export const UPDATE_DATA = ns('UPDATE_DATA');
export const RESET_DATA = ns('RESET_DATA');
export const SET_ERRORS = ns('SET_ERRORS');

export function updateData(data) {
  return (dispatch) => {
    dispatch({
      type: UPDATE_DATA,
      data,
    });
  };
}

export function resetData() {
  return (dispatch) => {
    dispatch({
      type: RESET_DATA,
    });
  };
}

export function setErrors(message) {
  return (dispatch) => {
    dispatch({
      type: SET_ERRORS,
      errors: {
        ip_whitelist: message,
      },
    });
  };
}

export function getIpWhite() {
  return (dispatch) => {
    exceed
      .forceFetch({
        api: 'organization.ip_setting',
        params: {
          id: organization.id,
        },
      })
      .then((result) => {
        if (!result.ip_whitelist_enabled) {
          dispatch(getLastIPWhite());
        }
        dispatch({
          type: RECEIVE_IP_WHITE_CHECK,
          data: result,
        });
      });
  };
}

/**
 * 使用流程：
 * 通过ip_setting接口判断是否开启白名单
 * 未开启白名单通过这个接口加载上次的IP设置
 * 注：
 * 只有关闭IP白名单时会保存当前设置，修改IP白名单设置的时候不会更新这个接口保存的设置
 * 用户未关闭过白名单，接口返回{"ip_whitelist_enabled":false}
 */
export function getLastIPWhite() {
  return (dispatch) => {
    dispatch(
      updateData({
        isLastIPLoading: true,
      }),
    );

    exceed
      .fetch({
        api: 'organization.last_ip_setting',
        params: {
          id: organization.id,
        },
      })
      .then((result) => {
        dispatch({
          type: RECEIVE_LAST_IP_WHITE_CHECK,
          data: result,
        });
      })
      .fail(() => {
        dispatch(
          updateData({
            isLastIPLoading: false,
          }),
        );
      });
  };
}

export function putIpWhite(data) {
  return () => {
    exceed
      .forceFetch({
        api: 'organization.ip_setting.put',
        params: {
          id: organization.id,
        },

        data,
      })
      .then((result) => {
        if (result.ip_whitelist_enabled) {
          Message.success({
            title: intl.get({
              id: 'code-assets.security.actions.WhitelistVerificationEnabled',
              defaultMessage: '已开启白名单验证',
            }),
          });

          window.location.reload();
        } else {
          Message.success({
            title: intl.get({
              id: 'code-assets.security.actions.WhitelistVerificationDisabled',
              defaultMessage: '已关闭白名单验证',
            }),
          });
        }
      });
  };
}

export function checkIpWhite(values, cb) {
  return (dispatch) => {
    exceed
      .fetch({
        api: 'organization.ip_setting.check',
        data: {
          ipList: values.ip_whitelist,
          remoteIp: remoteIP,
        },
      })
      .then((result) => {
        if (result.success) {
          dispatch(putIpWhite(values));
        } else {
          const ip = result.invalidIpList.join(' , ');
          if (result.invalidIpList && result.invalidIpList[0] !== remoteIP) {
            dispatch(
              setErrors(
                intl.get(
                  {
                    id: 'code-assets.security.actions.InvalidIpAddressIpEnter',
                    defaultMessage:
                      '存在非法 IP:  {ip}  ，请填写正确的ip地址范围 0.0.0.0~255.255.255.255',
                  },
                  { ip },
                ),
              ),
            );
          } else {
            dispatch(putIpWhite(values));
          }
        }
        cb && cb();
      })
      .fail(() => {
        cb && cb();
      });
  };
}
